#!/bin/bash

# 设置应用程序名称
APP_NAME="newsletter_subs"
# 设置应用程序的可执行文件路径
APP_PATH="/home/root/app/output/newsletter_subs"
# 设置应用程序的日志文件路径（可选）
LOG_FILE="/home/root/app/deploy.log"

# 记录日志的函数
log_message() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE" 2>&1
    echo "$1"
}

# 检查应用程序是否正在运行
is_running() {
    pgrep -x "$APP_NAME" > /dev/null 2>&1
    return $?
}

# 结束所有之前的进程
stop_application() {
    log_message "Stopping previous instances of $APP_NAME..."
    pkill -f "$APP_NAME" || true
}

# 启动新的应用程序
start_application() {
    log_message "Starting $APP_NAME..."
    nohup "$APP_PATH" > nohup &
    if [ $? -eq 0 ]; then
        log_message "$APP_NAME started successfully."
    else
        log_message "Failed to start $APP_NAME. Exiting script."
        exit 1
    fi
}

# 生成安全密钥
generate_security_key() {
    security_key=$(openssl rand -hex 32)
    export SECURITY_KEY=“$security_key”
    echo "Security key has been generated and exported as SECURITY_KEY." 
}

# 主程序
main() {
    # 停止之前的进
    stop_application
    
    # 启动新的应用程序
    start_application

    # 生成安全密钥
    generate_security_key
    
    log_message "Deployment of $APP_NAME completed."
}

# 执行主程序
main